import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
import os

def send_files_via_email(sender_email, sender_password, receiver_email, files, subject="文件发送"):
    """
    通过QQ邮箱发送文件
    
    参数:
        sender_email: 发送者邮箱
        sender_password: 发送者邮箱授权码（不是邮箱密码）
        receiver_email: 接收者邮箱
        files: 要发送的文件路径列表
        subject: 邮件主题
    """
    # 创建邮件对象
    msg = MIMEMultipart()
    msg['From'] = sender_email
    msg['To'] = receiver_email
    msg['Subject'] = subject

    # 添加邮件正文
    body = "这是一封自动发送的邮件，附件中包含所需文件。"
    msg.attach(MIMEText(body, 'plain'))

    # 添加附件
    for file_path in files:
        if os.path.exists(file_path):
            with open(file_path, 'rb') as f:
                attachment = MIMEApplication(f.read())
                attachment.add_header(
                    'Content-Disposition',
                    'attachment',
                    filename=os.path.basename(file_path)
                )
                msg.attach(attachment)

    # 连接QQ邮箱服务器并发送邮件
    try:
        server = smtplib.SMTP_SSL('smtp.qq.com', 465)
        server.login(sender_email, sender_password)
        server.send_message(msg)
        server.quit()
        print("邮件发送成功！")
        return True
    except Exception as e:
        print(f"发送邮件时出错: {str(e)}")
        return False

if __name__ == "__main__":
    # 示例使用
    sender = "2698471124@qq.com"
    password = "dxnoogxmmquudgbi"  # QQ邮箱授权码
    receiver = "2698471124@qq.com"
    files_to_send = ["labelExcel.xlsx"]
    
    send_files_via_email(sender, password, receiver, files_to_send)